package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.auth.utils.JwtUtils;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * 读取到clientId和secret之后，向ly-auth发出请求，申请秘钥
 * 完成秘钥加载，完成对JwtUtils的初始化：
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(ClientProperties.class)
@ConditionalOnProperty(prefix = "ly.auth", name = {"clientId", "secret"})
@EnableFeignClients(basePackages = "com.leyou.auth.client")
public class AuthConfiguration {
    @Autowired
    private AuthClient authClient;
    @Autowired
    private ClientProperties prop;

    @Bean
    @Primary
    public JwtUtils jwtUtils(){
        //向ly-auth发送请求，申请密匙
        while (true){
            try{
                //查询密匙
                String key = authClient.getSecretKey(prop.getClientId(), prop.getSecret());
                //创建jwtUtils
                JwtUtils jwtUtils = new JwtUtils(key);
                log.info("加载密匙成功");
                return jwtUtils;
            }catch (FeignException e){
                log.error("加载密匙失败，原因{}",e.contentUTF8());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}
